// pages/settings/update/update.js
var ble = require('../../../utils/bluetooth.js');
var event = require('../../../utils/event.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currVersion:1,
    latestVersion:2,
    ifBleConnected:false,
    index:null,
    deviceName:null,
    isUpgrading:false,
    progress:0,
    reconnect:false,
    content:'',
    progress_txt:'0%',
    count: 0, // 设置 计数器 初始为0
    countTimer: null, // 设置 定时器 初始为null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({ latestVersion : app.globalData.latestVersion});
    that.data.index = options.index;
    // console.log(app.globalData.kvStorage.deviceList[that.data.index].deviceName);
    that.data.deviceName = app.globalData.kvStorage.deviceList[that.data.index].deviceName;
    // that.data.ifBleConnected = app.globalData.BLE.connected

    // event.$on('BLE-connected-event', (sts) => {
    //   that.data.ifBleConnected = sts
    // })

    event.$on('upgrade-request-event', async function () {  //发送升级请求
      console.log('upgrade-request-event')
      for (let i = 0; i < 6; i++) {
        if (app.globalData.stopUpgrade) {
          break
        }
        var res0 = await ble.sendMsg(0x08, null, null, null)
        console.log("res0", res0)
        if (res0 == 8) {
          app.globalData.bletype = 3;
          that.data.reconnect = false;
          console.log(that.data.isUpgrading)
          event.$fire('upgrade-data-event')       //发送升级数据
          break
        } else if (res0 == -1) {                 //发送升级请求未收到回复
          if (i == 5) {
            event.$fire('upgrade-error-event',0)
          }
          continue
        } else if (res0 == -2) {                  //发送升级请求断线重连
          console.log('reconnect!!!')
          if(!that.data.reconnect){
            ble.Search()
            that.data.reconnect = true
          }else{
            event.$fire('upgrade-error-event',1)
          }
          break
        }
      }
    })

    event.$on('upgrade-data-event', async function () {                   //发送升级数据
      that.setData({
        isUpgrading: true,
        content: '正在发送升级数据包...'
      })
      var sn = Math.ceil(app.globalData.upgradeData.byteLength / 1024)
      var res1 = await ble.sendMsg(0x09, null, app.globalData.upgradeData, sn)  //发送升级数据
      console.log('res1', res1)
      wx.hideLoading()
      if (res1 == 9) {                                            //发送升级数据成功
        that.data.reconnect = false;
        app.globalData.bletype = 4;
        // wx.showLoading({
        //   title: '正在升级',
        // })
        
        event.$fire('upgrade-finish-event')
      } else if (res1 != -3) {
        event.$fire('upgrade-error-event', 2)         //发送升级数据失败
      }
    })

    event.$on('upgrade-finish-event', async function () {                   //发送完成请求
      that.setData({
        isUpgrading: true,
        content: '正在升级设备...'
      })
      var sn = Math.ceil(app.globalData.upgradeData.byteLength / 1024)
      var content = app.globalData.upgradeData.byteLength
      for (let k = 0; k < 5; k++) {
        if (app.globalData.stopUpgrade) {
          break
        }
        var res2 = await ble.sendMsg(0x0a, null, content, sn)    //发送完成请求
        console.log('res2', res2)
        wx.hideLoading()
        if (res2 == 10) {                                             //发送完成请求成功
          that.data.reconnect = false;
          wx.showToast({
            title: '升级成功',
            icon: 'success',
            duration: 1000
          })
          event.$fire('upgrade-ready-event')
          break
        } else if (res2 == -1) {                                              //发送完成请求失败
          if (k == 4) {
            event.$fire('upgrade-error-event',3)
          }
          continue
        } else if (res2 == -2) {                                             //发送完成请求断线重连
          console.log('reconnect!!!')
          if(!that.data.reconnect){
            ble.Search()
            that.data.reconnect = true
          }else{
            event.$fire('upgrade-error-event',4)
          }
          break
        }
      }
    })
         
    event.$on('upgrade-error-event', (data) => {
      that.setData({isUpgrading:false})
    //  that.data.ifBleConnected = false
      wx.showToast({
        title: '升级失败' + data,
        duration: 1000,
        image: '/images/fail.png'
      })
    })

    event.$on('upgrade-ready-event', () => {
      that.setData({ isUpgrading: false })
    })
    
    // event.$on('upgrade-event',(data)=>{
    //   ble.SendUpgrade(app.globalData.upgradeData).catch(function () {   //发送升级数据
    //     event.$fire('upgrade-error-event')
    //   })
    // })

    event.$on('upgrade-progress', (data) => {               //更新升级进度
      var progress = Math.ceil((data * 1024 / app.globalData.upgradeData.byteLength) * 100 )+ 1
      console.log('progress:', progress)
      // that.setData({ progress: (progress < 100) ? progress : 100})
      var pos = (progress < 100) ? progress : 100
      this.drawCircle(pos / 100 * 2)
      this.setData({
        progress_txt: pos + '%'
      });
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.drawProgressbg()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    event.$off('upgrade-request-event')
    event.$off('upgrade-data-event')
    event.$off('upgrade-finish-event')
    event.$off('upgrade-error-event')
    event.$off('upgrade-ready-event')
    event.$off('upgrade-progress')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 立即升级
   */
  update: function () {
    app.globalData.stopUpgrade = false
    var that = this;
    if (that.data.currVersion == that.data.latestVersion){
      //不需要更新
      return
    }
    else{
      //更新
      console.log("开始更新")
      that.setData({
        isUpgrading: true,
        progress: 0,
        content: '正在发送升级命令...',
        progress_txt: '0%'
      })
      that.drawProgressbg()
      app.globalData.bletype = 2;
      that.data.reconnect = false;
      if (app.globalData.BLE.connected && (app.globalData.BLE.deviceName == that.data.deviceName)) { //蓝牙已连接 that.data.deviceName
        console.log("蓝牙已连接")
        event.$fire('upgrade-request-event')
      }
      else {  //蓝牙未连接或连接了其他设备
      //  that.setData({ isUpgrading: true })
        app.globalData.BLE.deviceName = that.data.deviceName
        console.log("蓝牙未连接或连接了其他设备")
        ble.Search()
      }
    }
  },

  drawProgressbg: function () {
    // 使用 wx.createContext 获取绘图上下文 context
    var ctx = wx.createCanvasContext('canvasProgressbg')
    ctx.setLineWidth(2); // 设置圆环的宽度
    ctx.setStrokeStyle('#20183b'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath(); //开始一个新的路径
    ctx.arc(110, 110, 100, 0, 2 * Math.PI, false);
    //设置一个原点(100,100)，半径为90的圆的路径到当前路径
    ctx.stroke(); //对当前路径进行描边
    ctx.draw();
  },

  drawCircle: function (step) {
    var context = wx.createCanvasContext('canvasProgress');
    // 设置渐变
    var gradient = context.createLinearGradient(200, 100, 100, 200);
    gradient.addColorStop("0", "#2661DD");
    gradient.addColorStop("0.5", "#40ED94");
    gradient.addColorStop("1.0", "#5956CC");

    context.setLineWidth(10);
    context.setStrokeStyle(gradient);
    context.setLineCap('round')
    context.beginPath();
    // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
    context.arc(110, 110, 100, -Math.PI / 2, step * Math.PI - Math.PI / 2, false);
    context.stroke();
    context.draw()
  },

  countInterval: function () {
    // 设置倒计时 定时器 每100毫秒执行一次，计数器count+1 ,耗时6秒绘一圈
    this.countTimer = setInterval(() => {
      if (this.data.count <= 60) {
        /* 绘制彩色圆环进度条 
        注意此处 传参 step 取值范围是0到2，
        所以 计数器 最大值 60 对应 2 做处理，计数器count=60的时候step=2
        */
        this.drawCircle(this.data.count / (60 / 2))
        this.data.count++;
        this.setData({
          progress_txt: this.data.count
        });
      } else {
        clearInterval(this.countTimer);
      }
    }, 100)
  },

  handlerGobackClick() {
    var that = this
    const pages = getCurrentPages()
    if (that.data.isUpgrading) {
      wx.showModal({
        title: '提示',
        content: '正在升级中，是否取消升级',
        success: e => {
          if (e.confirm) {
            if (pages.length >= 2) {
              app.globalData.stopUpgrade = true
              wx.navigateBack({
                delta: 1
              })
            } else {
              // wx.navigateTo({
              //   url: '/pages/index/index'
              // });
            }
          }
        }
      })
    } else {
      if (pages.length >= 2) {
        app.globalData.stopUpgrade = true
        wx.navigateBack({
          delta: 1
        })
      }
    }
  },
})